﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using MiniCrawler.DataAccess;
using MiniCrawler.DataAccess.Repositories;
using MiniCrawler.Entity;
using MiniCrawler.UrlFilter;

namespace MiniCrawler.Downloader.ResourceDownloader
{
    public class LuuLLa : ResourceLinkCollector, IResourceCollector
    {
        private string hostName;

        public LuuLLa(string hostName, int level)
            : base(hostName, level)
        {
            this.hostName = hostName;
        }

        public string GetFolderPath(string data)
        {
            // Load data
            var doc = new HtmlDocument();
            doc.LoadHtml(data);


            var textString =
                "/html/body/div[@class='wrapper']" +
                "/div[@class='content-view-full margin-top-80']" +
                "/div[@class='product-details-full-page-misc width-980 capitalize margin-top-10 padding-bottom-20 float-left']" +
                "/div[@class='product-details-fullpage-top-title float-left width-576 bold font-size-20']";
            var authorString =
                "/html/body/div[@class='wrapper']" + "/div[@class='content-view-full margin-top-80']/div[@class='product-details-full-page-wrapper width-980 float-left']/div[@class='storefront-sideinfo-misc-wrapper width-370 min-height-300 margin-top-5 float-right']/div[@class='storefront-sideinfo-wrapper padding-25 background-color-f7f7f7 width-330 margin-top-20 margin-bottom-20 float-left']/div[@class='storefront-sideinfo-misc-sellerinfo-wrapper width-350 margin-bottom-20 float-left']/div[@class='store-info-sidebar-wrapper width-330 float-left']/div[@class='width-330 float-left']/div[@class='store-info-store-top-section-wrapper width-330 float-left']/div[@class='store-info-store-title-wrapper margin-right-10 float-left black-text-link margin-top-5 bold font-size-24']/a";


            var title = doc.DocumentNode.SelectSingleNode(textString).InnerText;
            var author = doc.DocumentNode.SelectSingleNode(authorString).InnerText;
            // Processing text
            // \ / : | ? * "
            string processedText =
                (author + ">" + title)
                    .Replace("&gt;", ">")
                    .Replace("&raquo;", ">")
                    .Replace("&amp;", "-")
                    .Replace(">", "\\")
                    .Replace("»", "\\")
                    .Replace('&', '-')
                    .Replace("/", string.Empty)
                    .Replace("|", string.Empty)
                    .Replace("?", string.Empty)
                    .Replace("*", string.Empty)
                    .Replace("\"", string.Empty)
                    .Replace(":", string.Empty)
                    .Replace("\r", string.Empty)
                    .Replace("\n", string.Empty)
                    .Replace("\t", string.Empty);
            if (processedText.Length > 255) processedText = processedText.Substring(0, 255);
            if (!string.IsNullOrEmpty(processedText))
                return processedText;
            else return "/";
        }

        public List<string> GetAllLinks(string data)
        {
            const string nodestring = "/html/body" +
                                      "/div[@class='wrapper']" +
                                      "/div[@class='content-view-full margin-top-80']" +
                                      "/div[@class='product-details-full-page-wrapper width-980 float-left']" +
                                      "/div[@class='product-details-full-page-content-wrapper width-576 float-left fullpage-middle-wrapper']" +
                                      "/div[@class='product-details-content-outer-wrapper width-576 float-left']" +
                                      "/div[@class='product-details-content-wrapper width-576 margin-top-5 float-left']" +
                                      "/div[@class='product-details-mul-image-wrapper margin-left-7 width-576 margin-top-15 padding-bottom-10 float-left']" +
                                      "/div[@class='product-details-mul-image-single-wrapper background-color-f7f7f7 padding-5 float-left']" +
                                      "/div[@class='cstore-product-detail-images-item-script float-left']";

            const string textString = "/html/body/div[@class='wrapper']" +
                                      "/div[@class='content-view-full margin-top-80']" +
                                      "/div[@class='product-details-full-page-misc width-980 capitalize margin-top-10 padding-bottom-20 float-left']" +
                                      "/div[@class='product-details-fullpage-top-title float-left width-576 bold font-size-20']";

            const string descriptionString = "/html/body/div[@class='wrapper']" +
                                             "/div[@class='content-view-full margin-top-80']" +
                                             "/div[@class='product-details-full-page-wrapper width-980 float-left']" +
                                             "/div[@class='product-details-full-page-content-wrapper width-576 float-left fullpage-middle-wrapper']" +
                                             "/div[@class='product-details-content-outer-wrapper width-576 float-left']" +
                                             "/div[@class='product-details-content-wrapper width-576 margin-top-5 float-left']" +
                                             "/div[@class='cstore-product-detail-product-description-item width-576 float-left margin-top-30 padding-bottom-20']";

            var doc = new HtmlDocument();
            doc.LoadHtml(data);


            // Select all category nodes with class = 'jazin-section'
            // Select id
            var root = doc.DocumentNode.SelectNodes(nodestring);
            var title = doc.DocumentNode.SelectSingleNode(textString).InnerText;
            var description = doc.DocumentNode.SelectSingleNode(descriptionString).InnerText;


            var result = new List<string>();
            foreach (var node in root)
            {
                string nodeHtml = node.InnerHtml;
                var t = FindStringBetween(nodeHtml, "http", "\"");
                if (t.Count > 0 && !string.IsNullOrEmpty(t[0])) result.Add(t[0]);
            }
            return result;
        }

        private List<string> FindStringBetween(string source, string start, string end)
        {
            var t = source.IndexOf(start);
            var result = new List<string>();

            while (t != null && t != -1)
            {
                string cutsource = source.Substring(t, source.Length - t);
                var z = cutsource.IndexOf(end);
                if (z != null && z != t)
                {
                    var s = cutsource.Substring(0, z);
                    cutsource = cutsource.Replace(s, string.Empty);
                    result.Add(s);
                    source = cutsource;
                    t = source.IndexOf(start);
                }
            }

            return result;
        }

        public List<string> GetResourcePatterns()
        {
            return new List<string>();
        }

        public void GetLinks()
        {
            foreach (var dataLink in Urls)
            {
                string data = Common.GetWebPage(Common.FillAbsoluteUrl(hostName, dataLink.Value));
                if(!string.IsNullOrEmpty(data))
                {
                    string folderPath = GetFolderPath(data);

                    var allLinks = GetAllLinks(data);

                    if(allLinks != null && allLinks.Count > 0)
                    {
                        foreach (var link in allLinks)
                        {
                            var downloadLink = 
                                new DownloadLink
                                    {
                                        Path = folderPath,
                                        Value = link,
                                        Website = dataLink.Website,
                                        IsDownloaded = false,
                                        Url = dataLink.Value
                                    };
                            DownloadLinkHelper.CreateLink(downloadLink);
                        }
                    }

                    DataLinkHelper.UpdateLink(dataLink.Value);
                }
            }
        }

        public void FixUrls()
        {
            DownloadLinkHelper.FixPathUrl(hostName);
        }
    }
}
